﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Grishko.DataTier.MetaInfo;
using Grishko.DataTier.SqlSentence;
using Grishko.SerilizeTools;

namespace Grishko.DataTier.SqlScriptor
{
    /// <summary>
    /// вспомогательный класс движка SqlScript.    
    /// Сформировать скрипт 
    /// </summary>
    public class ScriptCompareValuePropertyEngine
    {
        
        private SelectCommand selectCommand = null;
        public ScriptCompareValuePropertyEngine(SelectCommand cmd)
        {
            selectCommand = cmd;
        }

        public string GetScript()
        {
           int havingCount = 0;
           StringBuilder sb = new StringBuilder();  
           string format=   "INSERT INTO " + SqlScriptEngine.ScriptConst_SelectedObjectId + Environment.NewLine +
                            "SELECT ObjectID FROM  #SelectedObjectId_Condition " + Environment.NewLine +
                            "GROUP BY ObjectID  HAVING count(ObjectID) ={0}";
            sb.Append ("CREATE TABLE #SelectedObjectId_Condition(ObjectID varchar(36))");
            GetPopulateSelectedObjectIdScript(sb, out havingCount, "Property");            
            sb.Append(string.Format(format, havingCount));
            return sb.ToString();
        }

        /// <summary>
        //// вернуть условие отбора.
        /// </summary>
        /// <returns></returns>
        private void  GetPopulateSelectedObjectIdScript(
                                                         StringBuilder writer,   
                                                         out int havingCount, 
                                                         string tabPref)
        {
            string format = "INSERT INTO #SelectedObjectId_Condition " + Environment.NewLine +
                           "SELECT DISTINCT " + Environment.NewLine +
                           "Property.ObjectID	" + Environment.NewLine +
                           "FROM " + Environment.NewLine +
                            "#PopulatedObjectTree  Property WHERE {0}";

          StringBuilder sb = new StringBuilder();  
          /// Сформировать группы   
          List<List<Word>> words=  selectCommand.GetSetOfAndOrConditions();
          string sCurrentSql = string.Empty;
          int orCounter = 0;
          int j = 0;
          string sWhere = string.Empty;  
          // для каждой группы составить insert
          // выражение отвечает условиям если соответсвует всем группам 
          StringBuilder whereGroupBuilder = new StringBuilder();

          foreach (List<Word> itemList in words)
          {
              //sb.Append("(");
              for (int i = 0; i < itemList.Count; i++)
              {
                  //уcловие для слова
                  sCurrentSql = "(" + itemList[i].GetSql(true, tabPref) + ")";                                    
                  sWhere = (i == 0 ? string.Empty : " OR ") + sCurrentSql;
                  //копим условия для группы
                  whereGroupBuilder.Append(sWhere); 

              }
              string s = whereGroupBuilder.ToString();
              // вставка скрипта по группе              
              if (j < words.Count - 1)
                  orCounter++;
              j++;
              sCurrentSql = whereGroupBuilder.ToString()+Environment .NewLine ;
              // пишем очередное условие 
              writer.Append(string .Format (format ,sCurrentSql));
              whereGroupBuilder = new StringBuilder();
          }

          havingCount = words.Count;          
        }

        
    }
}
